package utils;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class KafkaClient {
    private static Producer<String, String> producer;

    public KafkaClient(String bootstrapServers,String id) {
        Properties kafkaProperties = new Properties();
        kafkaProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        kafkaProperties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, id);
        kafkaProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        kafkaProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        producer = new KafkaProducer<>(kafkaProperties);
    }

    public void createKafkaConnect() {
        producer.initTransactions();
        producer.beginTransaction();
    }

    public static void sendMessage( String value) {
        try {
            ProducerRecord<String, String> record = new ProducerRecord<>("appLogs", value);
            producer.send(record).get();// 使用.get()等待消息发送完成
            producer.commitTransaction();
        } catch (InterruptedException | ExecutionException e) {
            producer.abortTransaction();
            e.printStackTrace();
        }
    }

    public void close() {
        producer.close();
    }
}
